package com.dxf.sysadmin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dxf.common.utils.RedisUtil;
import com.dxf.common.utils.ResultJson;
import com.dxf.securitys.entity.SecurityUser;
import com.dxf.securitys.security.TokenManager;
import com.dxf.sysadmin.entity.SysFunc;
import com.dxf.sysadmin.entity.SysMenu;
import com.dxf.sysadmin.entity.SysUser;
import com.dxf.sysadmin.entity.po.TreeSelectPo;
import com.dxf.sysadmin.entity.vo.MenuVo;
import com.dxf.sysadmin.mapper.SysMenuMapper;
import com.dxf.sysadmin.service.SysFuncService;
import com.dxf.sysadmin.service.SysMenuService;
import com.dxf.sysadmin.service.SysUserService;
import com.dxf.sysadmin.service.UserRoleService;
import com.dxf.sysadmin.utils.MenuTree;
import com.dxf.sysadmin.utils.TreeHpler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * 菜单表 服务实现类
 */
@Slf4j
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysFuncService sysFuncService;
    @Autowired
    private TokenManager tokenManager;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     *获取菜单treeTable数据
     */
    @Override
    public ResultJson getMenus() {
        return ResultJson.ok().data("treeTable",
                TreeHpler.getMenuTree(sysMenuService,sysFuncService));
    }

    /**
     *菜单添加时父级选择的SelectTree数据
     */
    @Override
    public ResultJson selectTree() {
        return ResultJson.ok().data("selectTree",
                TreeHpler.getSelectTree(sysMenuService));
    }

    /**
     *提交menuForm添加或修改菜单(操作)
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultJson menuForm(TreeSelectPo po) {
        if (po.getId()!=null){
            //修改
            if ("0".equals(po.getIsMenu()) || "1".equals(po.getIsMenu())){
                SysMenu sysMenu = new SysMenu();
                BeanUtils.copyProperties(po,sysMenu);
                updateById(sysMenu);
            }else if ("2".equals(po.getIsMenu())){
                SysFunc sysFunc = new SysFunc();
                BeanUtils.copyProperties(po,sysFunc);
                sysFuncService.updateById(sysFunc);
            }
        }else {
            //添加
            String parentId=po.getParentId();
            String authority=po.getAuthority();
            if (StringUtils.isEmpty(parentId) && StringUtils.isEmpty(authority)){
                //添加主菜单
                log.info("=====pid={}===添加主菜单==auth={}===",parentId,authority);
                SysMenu sysMenu = new SysMenu();
                BeanUtils.copyProperties(po,sysMenu);
                sysMenu.setParentId((long) 0);
                save(sysMenu);
            }else if (!StringUtils.isEmpty(parentId) && StringUtils.isEmpty(authority)){
                //添加子菜单
                log.info("=====pid={}==添加子菜单===auth={}===",parentId,authority);
                SysMenu sysMenu = new SysMenu();
                BeanUtils.copyProperties(po,sysMenu);
                sysMenu.setParentId(Long.valueOf(po.getParentId()));
                save(sysMenu);
                //携带默认操作
                SysFunc detail=new SysFunc();
                detail.setName("查看");
                detail.setMenuId(sysMenu.getId());
                detail.setSortCode(10);
                detail.setAuthority("detail");
                sysFuncService.save(detail);
                SysFunc modiy=new SysFunc();
                modiy.setName("修改");
                modiy.setMenuId(sysMenu.getId());
                modiy.setSortCode(20);
                modiy.setAuthority("modiy");
                sysFuncService.save(modiy);
                SysFunc delete=new SysFunc();
                delete.setName("删除");
                delete.setMenuId(sysMenu.getId());
                delete.setSortCode(30);
                delete.setAuthority("delete");
                sysFuncService.save(delete);
                SysFunc add=new SysFunc();
                add.setName("添加");
                add.setMenuId(sysMenu.getId());
                add.setSortCode(40);
                add.setAuthority("add");
                sysFuncService.save(add);
            }else if (!StringUtils.isEmpty(parentId) && !StringUtils.isEmpty(authority)){
                //添加操作
                log.info("=====pid={}==添加操作===auth={}===",parentId,authority);
                SysFunc sysFunc = new SysFunc();
                BeanUtils.copyProperties(po,sysFunc);
                sysFunc.setMenuId(Long.valueOf(po.getParentId()));
                sysFuncService.save(sysFunc);
            }
        }
        return ResultJson.ok();
    }

    /**
     *更具MenuTree对象判断删除菜单（操作）
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultJson deleteMenu(MenuTree tree) {
        String isMenu=tree.getIsMenu();
        if ("0".equals(isMenu)){
            //删除主菜单
            removeById(tree.getId());
            List<SysMenu> list = list(new QueryWrapper<SysMenu>().lambda().
                    eq(SysMenu::getParentId, tree.getId()));
            list.forEach(x->{
                //删除操作
                sysFuncService.remove(new QueryWrapper<SysFunc>().lambda().
                        eq(SysFunc::getMenuId,x.getId()));
            });
            //删除子菜单
            remove(new QueryWrapper<SysMenu>().lambda().
                    eq(SysMenu::getParentId,tree.getId()));

        }else if("1".equals(isMenu)){
            //删除子菜单
            removeById(tree.getId());
            //删除操作
            sysFuncService.remove(new QueryWrapper<SysFunc>().lambda().
                    eq(SysFunc::getMenuId,tree.getId()));

        }else if("2".equals(isMenu)){
            //删除操作
            sysFuncService.remove(new QueryWrapper<SysFunc>().lambda().
                    eq(SysFunc::getId,tree.getId()));
        }
        return ResultJson.ok();
    }

    /**
     *更具token获取菜单
     */
    @Override
    public ResultJson menuVo(String token) {
        //空列表
        List  nullList=new ArrayList();
        //返回数据
        List<MenuVo> list=new ArrayList<>();
        String userName = tokenManager.getUserFromToken(token);
        SecurityUser user = (SecurityUser) redisUtil.get(userName);
        //用户菜单
        List<SysMenu> sysMenus = baseMapper.selectSysMenuByUserId(user.getCurrentUserInfo().getId());
        sysMenus.forEach(x->{
            if (x.getParentId()==0){
                //父级
                MenuVo menuVo = new MenuVo(x.getName(),x.getImgUrl(),x.getAppUrl());
                List<SysMenu> collect = sysMenus.stream().filter(a -> a.getParentId().equals( x.getId()) ).collect(Collectors.toList());
                List<MenuVo> list2=new ArrayList<>();
                collect.forEach(y->{
                    //子级
                    MenuVo menuVo2 = new MenuVo(y.getName(),y.getImgUrl(),y.getAppUrl());
                    menuVo2.setList(nullList);
                    list2.add(menuVo2);
                });
                menuVo.setList(list2);
                list.add(menuVo);
            }
        });
        return ResultJson.ok().data("menuVo",list);
    }
}
